// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/testing/gtest_utils.h>
#include <pollux/testing/functions/prestosql/function_base_test.h>
#include <pollux/functions/prestosql/types/bing_tile_type.h>

namespace kumo::pollux::functions::prestosql {

namespace {

class BingTileCastTest : public functions::test::FunctionBaseTest {
 protected:
  std::optional<int64_t> castToBigintRoundtrip(std::optional<int64_t> input) {
    std::optional<int64_t> result =
        evaluateOnce<int64_t>("cast(cast(c0 as bingtile) as bigint)", input);
    return result;
  }
};

TEST_F(BingTileCastTest, roundtrip) {
  auto assertRoundtrip = [this](int32_t x, int32_t y, int8_t zoom) {
    std::optional<int64_t> result_bigint = castToBigintRoundtrip(
        (int64_t)BingTileType::bingTileCoordsToInt(x, y, zoom));
    ASSERT_TRUE(result_bigint.has_value());
    uint64_t tile = static_cast<uint64_t>(result_bigint.value());
    ASSERT_TRUE(BingTileType::isBingTileIntValid(tile));
    ASSERT_EQ(BingTileType::bingTileZoom(tile), zoom);
    ASSERT_EQ(BingTileType::bingTileX(tile), x);
    ASSERT_EQ(BingTileType::bingTileY(tile), y);
  };

  assertRoundtrip(0, 0, 0);
  assertRoundtrip(123, 111, 7);
}

TEST_F(BingTileCastTest, errors) {
  POLLUX_ASSERT_USER_THROW(
      evaluateOnce<int64_t>(
          "cast(c0 as bingtile)",
          std::optional((int64_t)BingTileType::bingTileCoordsToInt(0, 1, 0))),
      "Y coordinate 1 is greater than max coordinate 0 at zoom 0");
}

} // namespace

} // namespace kumo::pollux::functions::prestosql
